package rpg.writer.app.player;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.swing.JButton;
import javax.swing.JPanel;

import rpg.client.Instruction;

class InstructionButton extends JButton {
    /**
     * 
     */
    private static final long serialVersionUID = 6106709889199443024L;
    private final Instruction instruction;

    InstructionButton(Instruction i, ActionListener listener) {
        super(i.toString());
        instruction = i;
        this.addActionListener(listener);
    }

    Instruction getInstruction() {
        return instruction;
    }
}

public class InstructionJPanel extends JPanel implements ActionListener {
    /**
     * 
     */
    private static final long serialVersionUID = 4201266694432350996L;

    private final Map<Instruction, InstructionButton> buttonMap = new ConcurrentHashMap<Instruction, InstructionButton>();
    private final PlayerJPanel player;

    public InstructionJPanel(PlayerJPanel c) {
        super(new GridLayout(10, 1));
        this.setPreferredSize(new Dimension(400, 400));
        player = c;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(e);
        if (e.getSource() instanceof InstructionButton) {
            InstructionButton ib = (InstructionButton) e.getSource();
            player.sendInstruction(ib.getInstruction());
        }
    }

    public boolean update(List<Instruction> possibleInstructions) {
        boolean doUpdate = (possibleInstructions.size() != buttonMap.size());

        if (!doUpdate) {
            if (possibleInstructions.size() == buttonMap.size()) {
                for (Instruction i : possibleInstructions) {
                    if (buttonMap.containsKey(i)) {
                        doUpdate = true;
                        break;
                    }
                }
            }
        }

        if (doUpdate) {
            for (InstructionButton ib : buttonMap.values()) {
                ib.removeActionListener(this);
                remove(ib);
            }
            buttonMap.clear();

            for (Instruction i : possibleInstructions) {
                InstructionButton ib = new InstructionButton(i, this);
                buttonMap.put(i, ib);
                add(ib);
            }
        }

        return doUpdate;
    }
}
